package TCP.EchoServer;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * 客户端
 */
public class TcpEchoClient {

    private Socket socket = null;

    public TcpEchoClient(String IP, int port) throws IOException {
        socket = new Socket(IP,port);
    }
    public void start(){
        System.out.println("连接成功");
        Scanner scanner = new Scanner(System.in);

        try(InputStream inputStream = socket.getInputStream()) {
            try(OutputStream outputStream = socket.getOutputStream()){
                while (true){
                    String request = scanner.next();

                    PrintWriter printWriter = new PrintWriter(outputStream);
                    printWriter.println(request);
                    printWriter.flush();

                    // 响应Scanner
                    Scanner responseScanner = new Scanner(inputStream);
                    String response = responseScanner.nextLine();
                    System.out.println(response);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient("127.0.0.1", 9090);
        client.start();
    }
}
